package cn.ibizlab.util.security;

import cn.ibizlab.util.service.AuthenticationUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.ObjectUtils;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Slf4j
@Component
public class AuthorizationTokenFilter extends OncePerRequestFilter {

    private final UserDetailsService userDetailsService;

    private final String tokenHeader;

    @Value("${ibiz.auth.excludesPattern:}")
    private String[] excludesPattens;

    private PathMatcher pathMatcher = new AntPathMatcher();

    private boolean isExclusion(String requestURI) {
        if (excludesPattens == null) {
            return false;
        } else {
            for(String pattern:excludesPattens) {
                if(pathMatcher.match(pattern, requestURI))
                    return true;
            }
            return false;
        }
    }

    public AuthorizationTokenFilter(UserDetailsService userDetailsService, @Value("${ibiz.jwt.header:Authorization}") String tokenHeader) {
        this.userDetailsService = userDetailsService;
        this.tokenHeader = tokenHeader;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        if (isExclusion(request.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }

        if(SecurityContextHolder.getContext().getAuthentication() != null){
            chain.doFilter(request, response);
            return;
        }

        String requestHeader = request.getHeader(this.tokenHeader);

        if(!"Authorization".equalsIgnoreCase(tokenHeader) && ObjectUtils.isEmpty(requestHeader))
            requestHeader = request.getHeader("Authorization");

        String username = null;
        String authToken = null;
        if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
            authToken = requestHeader.substring(7);
            try {
                username = ((AuthenticationUserService)userDetailsService).getUsernameFromToken(authToken);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }

        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
            boolean validate = true;
            if(userDetailsService instanceof AuthenticationUserService) {
                validate = ((AuthenticationUserService)userDetailsService).validateToken(authToken, userDetails);
                if(userDetails instanceof AuthenticationUser) {
                    AuthenticationUser curUser = ((AuthenticationUser) userDetails);
                    curUser.readHeader(false);
                    if (!ObjectUtils.isEmpty(curUser.getOrganizationId())) {
                        Map<String, List<String>> orgInfo = ((AuthenticationUserService)userDetailsService).getOrgInfo(curUser.getOrganizationId(), curUser.getDepartmentId()==null?"null": curUser.getDepartmentId());
                        curUser.getParentOrgIds().addAll(orgInfo.getOrDefault("organization_parent_ids",Collections.emptyList()));
                        curUser.getSubOrgIds().addAll(orgInfo.getOrDefault("organization_sub_ids",Collections.emptyList()));
                        curUser.getParentDeptIds().addAll(orgInfo.getOrDefault("department_parent_ids",Collections.emptyList()));
                        curUser.getCurOrgIds().addAll(orgInfo.getOrDefault("department_sub_ids",Collections.emptyList()));
                    }
                    AuthenticationContextHolder.setContext((AuthenticationUser)userDetails);
                }
            }
            if (validate) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        chain.doFilter(request, response);
    }

}
